package cn.tom.controller.fore;

import cn.tom.tools.TokenAndUser;
import cn.tom.tools.XJson;
import cn.tom.tools.XResp;
import cn.tom.entity.*;
import cn.tom.service.CartService;
import cn.tom.service.OrderService;
import cn.tom.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/api/fore/cart")
public class foreCartController {
    @Resource
    private CartService cartService;
    @Resource
    private OrderService orderService;

    @GetMapping("/findMyCarts")
    public XJson findAllByUid(){
        XUser xUser = (XUser) TokenAndUser.findOne().getData();
        List<Cart> lst = cartService.findByUid(xUser.getId());
        log.info(lst.toString());
        return XResp.pack(200,"",lst);
    }

    @PostMapping("/add2Order")
    public XJson add2Order(@RequestBody Cart2Ord cart20rd)
    {
        Order order = null;
        try{
              order = orderService.add2Order(cart20rd);
        }catch (MyException e) {
            return XResp.pack(501, e.getMessage(), null);
        }
        if(order.getOrdid() == 0) return XResp.pack(501,"下单失败",null);
        Map<String,Object> map = new HashMap<>();
        map.put("ordid"   ,order.getOrdid());
        map.put("amount"  ,order.getAmount());
        return XResp.pack(200,"成功接收到数据，并产生订单....",map);
    }
}
